package com.store.app.activity;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * author xmn
 * on 2017/2/24 17:20
 * 雷达页面
 */
public class LeidaActivity extends BaseActivity  implements BDLocationListener, IOnHttpListener,OnGetGeoCoderResultListener {
    private ImageView back;
    private MapView mapView;
    private BaiduMap mBaidumap;
    // 定位相关
    private LocationClient mLocClient;
    private MyLocationConfiguration.LocationMode mCurrentMode;

    private LinearLayout linearLayout;
    private TextView tv_name,tv_add;
    /**当前位置维度*/
    private double d_latitude;
    /**当前位置经度*/
    private double d_longitude;
    private LatLng pt = null;
    private BitmapDescriptor bitmap;
    private NetRequest netRequest;
    private String groupid;
    private List<leidabean> leidalist=new ArrayList<>();
    private GeoCoder mSearch = null; // 搜索模块，也可去掉地图模块独立使用
    private Map<Integer,View> map=new HashMap<>();
    private Handler handler = new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_leida);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        ExitApplication.getInstance().addActivity(this);
        initViews();
        initListeners();

    }

    private void initListeners() {
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initViews() {
        groupid = getIntent().getStringExtra("groupid");
        netRequest = new NetRequest(this);


        bitmap = BitmapDescriptorFactory.fromResource(R.drawable.local);
        back= (ImageView) findViewById(R.id.retreat);
        mapView = (MapView) findViewById(R.id.map);
        linearLayout= (LinearLayout) findViewById(R.id.map_lin);

        tv_name= (TextView) findViewById(R.id.map_name);
        tv_add= (TextView) findViewById(R.id.map_add);
        mBaidumap = mapView.getMap();
        mBaidumap.setMapType(BaiduMap.MAP_TYPE_NORMAL); //普通地图
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        mBaidumap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode, true, null));
        mBaidumap.setMyLocationEnabled(true); // 开启定位图层
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(this); //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(false);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(0);
        option.setIsNeedAddress(true); //可选，设置是否需要地址信息，默认不需要
        mLocClient.setLocOption(option);
        mLocClient.start();

        // 初始化搜索模块，注册事件监听
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);

        mBaidumap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                tv_name.setText("");
                tv_add.setText("");
                linearLayout.setVisibility(View.GONE);
            }
            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });
       //overlay点击事件
        mBaidumap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                linearLayout.setVisibility(View.VISIBLE);
                Bundle bundle = marker.getExtraInfo();
                if (bundle != null) {
                    int i = bundle.getInt("position");
                    tv_name.setText(leidalist.get(i).getNickname());
                    try {
                        String s_latitude = leidalist.get(i).getLatitude();
                        String s_longitude = leidalist.get(i).getLongitude();
                        Double d_latitude_item = Double.parseDouble(s_latitude);
                        Double d_longitude_item = Double.parseDouble(s_longitude);
                        LatLng ptCenter = new LatLng(d_latitude_item,d_longitude_item);
                        // 反Geo搜索
                        mSearch.reverseGeoCode(new ReverseGeoCodeOption()
                                .location(ptCenter));
                    }catch (Exception e){

                    }
                }
                return false;
            }
        });
    }

    @Override
    public  void onPause() {
        mapView.onPause();
        super.onPause();
    }

    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }
    @Override
    protected void onDestroy() {
        try{
            bitmap.recycle();
        }catch (Exception e){

        }
        mBaidumap.clear();
        mapView.onDestroy();
        mLocClient.stop();
        mBaidumap.setMyLocationEnabled(false);
        super.onDestroy();
    }
  //点位监听
    @Override
    public void onReceiveLocation(BDLocation location) {
        if (null != location
                && location.getLocType() != BDLocation.TypeServerError) {
            d_latitude = location.getLatitude();
            d_longitude = location.getLongitude();
            pt = new LatLng(d_latitude, d_longitude);
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(pt, 16);//设置地图默认1公里的范围
            mBaidumap.animateMapStatus(u);
            //overlay显示当前位置
            // 构建MarkerOption，用于在地图上添加Marker
            OverlayOptions option = new MarkerOptions().position(pt).icon(bitmap);
            // 在地图上添加Marker，并显示
            mBaidumap.addOverlay(option);
            netRequest.requestHXIMLeidaAccount(1, groupid);
        }
    }
    DisplayImageOptions options = new DisplayImageOptions.Builder()
            .cacheInMemory(true)
            .showImageOnLoading(R.drawable.ease_default_avatar)
            .showImageOnFail(R.drawable.ease_default_avatar)
            .showStubImage(R.drawable.ease_default_avatar)
            .imageScaleType(ImageScaleType.EXACTLY)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();

    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (result != null) {
            try {
                List<leidabean> leidaInfo=new ArrayList<>();
                JSONArray jsonArray=new JSONArray(result);
                for (int i=0;i<jsonArray.length();i++){
                  JSONObject jsonObject =jsonArray.getJSONObject(i);
                    leidabean leidabean=new leidabean();
                    leidabean.setHead_pic_path(jsonObject.getString("head_pic_path"));
                    leidabean.setIm_user_id(jsonObject.getString("im_user_id"));
                    try{
                        Double latitude=jsonObject.getDouble("latitude");
                        Double longitude=jsonObject.getDouble("longitude");
                        leidabean.setLatitude(latitude+"");
                        leidabean.setLongitude(longitude+"");
                    }catch (Exception e){
                        continue;
                    }
                    leidabean.setMember_id(jsonObject.getString("member_id"));
                    leidabean.setMember_type_key(jsonObject.getString("member_type_key"));
                    leidabean.setNickname(jsonObject.getString("nickname"));
                    leidaInfo.add(leidabean);
                }

                 //获取每一个view
                if (leidaInfo.size() > 0) {
                    leidalist=leidaInfo;
                    for(int i=0;i<leidaInfo.size();i++){
                        leidabean itembean=leidaInfo.get(i);
                        String s_latitude=itembean.getLatitude();
                        String s_longitude=itembean.getLongitude();
                        Double d_latitude_item=0.0;
                        Double d_longitude_item=0.0;
                        if(TextUtils.isEmpty(s_latitude)||TextUtils.isEmpty(s_longitude)){
                            continue;
                        }
                        try{
                            d_latitude_item=Double.parseDouble(s_latitude);
                            d_longitude_item=Double.parseDouble(s_longitude);
                        }catch (Exception e){
                            continue;
                        }

                        View view = LayoutInflater.from(this).inflate(R.layout.view_leida_overlay, null);
                        ImageView imageView = (ImageView) view.findViewById(R.id.iv_leida_userhead);
                        String img=itembean.getHead_pic_path();
                        if(!TextUtils.isEmpty(img)) {
                            ImageLoader.getInstance().displayImage(img,
                                    imageView, options);
                        }

                        map.put(i, view);}

                  //view加入地图
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            for(int i=0;i<leidalist.size();i++){
                                leidabean itembean=leidalist.get(i);

                                String s_latitude=itembean.getLatitude();
                                String s_longitude=itembean.getLongitude();
                                Double d_latitude_item=0.0;
                                Double d_longitude_item=0.0;
                                if(TextUtils.isEmpty(s_latitude)||TextUtils.isEmpty(s_longitude)){
                                    continue;
                                }
                                try{
                                    d_latitude_item=Double.parseDouble(s_latitude);
                                    d_longitude_item=Double.parseDouble(s_longitude);
                                }catch (Exception e){
                                    continue;
                                }
                                LatLng pt1 = new LatLng(d_latitude_item, d_longitude_item);
                                View view=map.get(i);
                                if(view==null){
                                    continue;
                                }
                                BitmapDescriptor bdGround = BitmapDescriptorFactory
                                        .fromView(view);
                                // 构建MarkerOption，用于在地图上添加Marker
                                Bundle bundle = new Bundle();
                                bundle.putInt("position", i);
                                OverlayOptions option = new MarkerOptions().position(pt1).icon(bdGround).extraInfo(bundle);
                                // 在地图上添加Marker，并显示
                                mBaidumap.addOverlay(option);
                            }

                        }
                    },3000);


                }



            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {

    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        final String s_add=reverseGeoCodeResult.getAddress();
        if(!TextUtils.isEmpty(s_add)) {
            tv_add.setText(reverseGeoCodeResult.getAddress());
        }
    }

    class leidabean{


        /**
         * head_pic_path : https://oss-img.meitianhui.com/test/communityDocs/201604/92a3406c4527484394cc0264c1fd41ff.png
         * im_user_id : 86d5b703b0f7472babc816c4bd9b5392
         * latitude : 22.5568315
         * longitude : 114.0737691
         * member_id : 11613920
         * member_type_key : consumer
         * nickname : 胖胖
         * sex_key :
         */

        private String head_pic_path;
        private String im_user_id;
        private String latitude;
        private String longitude;
        private String member_id;
        private String member_type_key;
        private String nickname;
        private String sex_key;

        public String getHead_pic_path() {
            return head_pic_path;
        }

        public void setHead_pic_path(String head_pic_path) {
            this.head_pic_path = head_pic_path;
        }

        public String getIm_user_id() {
            return im_user_id;
        }

        public void setIm_user_id(String im_user_id) {
            this.im_user_id = im_user_id;
        }

        public String getLatitude() {
            return latitude;
        }

        public void setLatitude(String latitude) {
            this.latitude = latitude;
        }

        public String getLongitude() {
            return longitude;
        }

        public void setLongitude(String longitude) {
            this.longitude = longitude;
        }

        public String getMember_id() {
            return member_id;
        }

        public void setMember_id(String member_id) {
            this.member_id = member_id;
        }

        public String getMember_type_key() {
            return member_type_key;
        }

        public void setMember_type_key(String member_type_key) {
            this.member_type_key = member_type_key;
        }

        public String getNickname() {
            return nickname;
        }

        public void setNickname(String nickname) {
            this.nickname = nickname;
        }

        public String getSex_key() {
            return sex_key;
        }

        public void setSex_key(String sex_key) {
            this.sex_key = sex_key;
        }

    }

}